package com.haoting.blogservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haoting.blogservice.entity.Blogsubject;
import com.haoting.blogservice.entity.excel.SubjectData;
import com.haoting.blogservice.service.BlogsubjectService;
import com.haoting.service.exceptionhandler.BlogException;

public class SubjectExcelListenser extends AnalysisEventListener<SubjectData> {

    public BlogsubjectService blogsubjectService;
    public SubjectExcelListenser(){}

    public SubjectExcelListenser(BlogsubjectService blogsubjectService) {
        this.blogsubjectService = blogsubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            throw new BlogException(20001,"文件数据为空");
        }

        Blogsubject oneSubject = this.existOneSubject(blogsubjectService,subjectData.getOneSubjectName());
        if(oneSubject == null){
            oneSubject = new Blogsubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());
            blogsubjectService.save(oneSubject);
        }

        String pid = oneSubject.getId();
        Blogsubject twoSubject = this.existTwoSubject(blogsubjectService,subjectData.getOneSubjectName(),pid);
        if(twoSubject == null){
            twoSubject = new Blogsubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            blogsubjectService.save(twoSubject);
        }

    }

    //判断一级分类不能重复添加
    private Blogsubject existOneSubject(BlogsubjectService blogsubjectService,String name){
        QueryWrapper<Blogsubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        Blogsubject blogsubject = blogsubjectService.getOne(wrapper);
        return blogsubject;
    }
    private Blogsubject existTwoSubject(BlogsubjectService blogsubjectService,String name,String pid){
        QueryWrapper<Blogsubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        Blogsubject blogsubject = blogsubjectService.getOne(wrapper);
        return blogsubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
